package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.QuestionnaireApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.*;
import com.tanhua.model.em.Dimensions;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.OptionVo;
import com.tanhua.model.vo.QQuestionVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TestSoulService {

    @DubboReference
    private QuestionnaireApi questionnaireApi;

    @Autowired
    private MqMessageService mqMessageService;

    @DubboReference
    private UserInfoApi userInfoApi;

    //查询 问卷
    public List<Questionnaire> findQuestionnaire() {
        //查询与用户相关的问卷表是否存在
        Map<String, UserQuestionnaire> map = questionnaireApi.findUQ(UserHolder.getUserId());
        //查询问卷
        List<Questionnaire> questionnaires = questionnaireApi.findQuestionnaire();
        //判断是否有问卷
        if (questionnaires == null || questionnaires.size() <= 0) {
            throw new BusinessException(ErrorResult.error());
        }
        //获取级别的数组
        List<String> ids = CollUtil.getFieldValues(questionnaires, "id", String.class);
        //不存在则创建,标记第一次出现
        boolean flag = true;
        if (map == null) {
            flag = false;
            for (String id : ids) {
                UserQuestionnaire uq = new UserQuestionnaire();
                uq.setUserId("" + UserHolder.getUserId());
                uq.setQuestionnaireId(id);
                questionnaireApi.saveUQ(uq);
            }
            //添加完后再次查询
            map = questionnaireApi.findUQ(UserHolder.getUserId());
        }
        //查询试题
            for (Questionnaire questionnaire : questionnaires) {
                //查询是否锁住
                UserQuestionnaire uq = map.get(questionnaire.getId());

                //判断是否是第一出现,第一次出现则修改初级问卷的锁定为解锁
                if (!flag) {
                    if (questionnaire.getLevel().equals("初级")) {
                        uq.setIsLock(0);
                        questionnaireApi.updateUQ(uq);
                    }
                }

            //是否锁定从数据库拉取,,,其他的由提交报告时试题的难度确认问卷等级进行修改相对应的锁定

            List<QQuestion> qQuestions = questionnaireApi.findQuestion(questionnaire.getLevel());
            List<QQuestionVo> qQuestionVos = new ArrayList<>();
            //判断是否有题目
            if (qQuestions == null || qQuestions.size() <= 0) {
                throw new BusinessException(ErrorResult.error());
            }
            for (QQuestion qQuestion : qQuestions) {
                List<OptionVo> options = questionnaireApi.findOption(qQuestion.getId());
                //组合
                qQuestion.setOptions(options.toArray());
                QQuestionVo vo = new QQuestionVo();
                BeanUtil.copyProperties(qQuestion, vo);
                vo.setId(qQuestion.getId().toString());
                qQuestionVos.add(vo);
            }
            //组合
            questionnaire.setQuestions(qQuestionVos.toArray());
             init(questionnaire, uq);
        }
        System.out.println(questionnaires);
        return questionnaires;
    }

    //用于组合uq和q的方法
    private Questionnaire init(Questionnaire questionnaire, UserQuestionnaire userQuestionnaire) {
        System.out.println(userQuestionnaire);
        questionnaire.setIsLock(userQuestionnaire.getIsLock());
        if (userQuestionnaire.getReportId() != null) {
            questionnaire.setReportId(userQuestionnaire.getReportId());
        }

        return questionnaire;
    }

    //问卷提交
    // 外向，判断，抽象，理性
    // 1:10  20    10   10
    /*
    // 外向，判断，抽象，理性
    // 1:30  25    0   10
       2:10  0    25   20
       3:10   40    30   0
       4:0   20  40    25

     */
    public String statistics(List<Answers> an) {
        //判断是否是第一次提交问卷
        String questionId = an.get(0).getQuestionId();

        //查询题目
        QQuestion qQuestion = questionnaireApi.findQuestionById(questionId);
        String level = qQuestion.getLevel();
        //查询是否重复提交
        Report reportExit = questionnaireApi.exitRepeatReport(UserHolder.getUserId(), level);
        if (reportExit != null) {
            //使用rmq删除已经存在的相似度表
            //删除以前的报告表
            questionnaireApi.deleteReport(UserHolder.getUserId(), level);
            mqMessageService.sendLogService(UserHolder.getUserId(), level, "delete.report", reportExit.getId() + "");
        }


        Dimensions extroversion = Dimensions.Extroversion;//外向
        Dimensions judge = Dimensions.Judge;//判断
        Dimensions anAbstract = Dimensions.Abstract;//抽象
        Dimensions reason = Dimensions.Reason;//理性


        //进行分数的计算
        for (Answers answers : an) {
            int i = Integer.valueOf(answers.getOptionId()) % 4;
            if (i == 1) {
                extroversion.Extra(30);
                judge.Extra(25);
                anAbstract.Extra(0);
                reason.Extra(10);
            }
            if (i == 2) {
                extroversion.Extra(10);
                judge.Extra(0);
                anAbstract.Extra(25);
                reason.Extra(20);
            }
            if (i == 3) {
                extroversion.Extra(25);
                judge.Extra(40);
                anAbstract.Extra(30);
                reason.Extra(0);
            }
            if (i == 4) {
                extroversion.Extra(0);
                judge.Extra(20);
                anAbstract.Extra(40);
                reason.Extra(25);
            }
        }
        //分数计算完毕
        Integer scoreEx = extroversion.getScore();//外向
        Integer scoreJu = judge.getScore();//判断
        Integer scoreAb = anAbstract.getScore();//抽象
        Integer scoreRe = reason.getScore();//理性
        int i = scoreAb + scoreEx + scoreJu + scoreRe;
        //维度
        Set<Extra> list = new HashSet<>();
        //外向添加
        Extra ee = new Extra();
        ee.setKeyOne("外向");
        ee.setValueOne(scoreEx + "%");
        list.add(ee);
        //判断添加
        Extra ej = new Extra();
        ej.setKeyOne("判断");
        ej.setValueOne(scoreJu + "%");
        list.add(ej);
        //抽象添加
        Extra ea = new Extra();
        ea.setKeyOne("抽象");
        ea.setValueOne(scoreAb + "%");
        list.add(ea);
        //理性添加
        Extra er = new Extra();
        er.setKeyOne("理性");
        er.setValueOne(scoreRe + "%");
        list.add(er);
        Report report = new Report();
        if (i > 200 && i <= 250) {
            report.setConclusion("兔子型");
            report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/tanhua/avatar_14.jpg");
        }
        if (i > 250) {
            report.setConclusion("狐狸型");
            report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/tanhua/avatar_14.jpg");
        }
        if (i <= 200) {
            report.setConclusion("菜狗");
            report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/tanhua/avatar_14.jpg");
        }
        report.setUserId(UserHolder.getUserId());
        report.setLevel(level);
        //添加入数据库返回报告Id
        String reportId = questionnaireApi.saveReport(report, list);

        //将报告id写入对应的数据库中
        questionnaireApi.saveUQReportId(reportId, level, UserHolder.getUserId());

        mqMessageService.sendLogService(UserHolder.getUserId(), level, "similar.report", null);
        if ("初级".equals(level)) {
            //解除中级问题表
            questionnaireApi.relieve(UserHolder.getUserId(), "中级");
        }
        if ("中级".equals(level)) {
            //解除高级问题表
            questionnaireApi.relieve(UserHolder.getUserId(), "高级");
        }
        return reportId;

    }

    //报告查询
    public Report findReport(Integer reportId) {
        //通过报告的id查询报告
        Report report = questionnaireApi.findByReportIdReprot(reportId);
        //通过报告的id查询维度值
        List<Extra> extras = questionnaireApi.findByReportIdExtra(reportId);
        //通过自己的userId,desc查询相似的人,如果没查到则为null;
        Similar similar = questionnaireApi.findByUserIdSimilar(UserHolder.getUserId());
        UserInfo userInfo = null;
        if (similar != null) {
            Long sUserId = similar.getSUserId();
            //去用户表里查询对应的用户信息
            userInfo = userInfoApi.findById(sUserId);
        }
        //组合返回值
        return Report.init(report, extras, userInfo);
    }
}
